import logging

from django.http import JsonResponse

from comment.comservice import add_filter
from comment.comviews import com_views, err_response, success_response, format_response
from utils.dbutils import DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))


def all_note_classify(params):
    """
    查询所有日志分类
    :param params:
    :return:
    """
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    sql = NoteSqlMap.FIND_ALL_CLASSIFY.format(**params)
    result_all = mysql_tools.select_all(sql)
    return success_response(result_all)


def note_add(params):
    dict = {
        "createman_id": "user_id",
        "catalog_id": "catalog_id",
        "content": "content",
        "title": "title",
    }
    null_params = {
        "receiver_id": "receiver_id",
        "attach_id": "attach_id"

    }
    params = get_params(params, dict, null_params)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if key in ["receiver_id", "attach_id"]:
    #         continue
    #     if val is None:
    #         return err_response(210)
    if not params.get("attach_id"):
        params["attach_id"] = "null"
    if params.get("receiver_id"):
        receiver = ""
        for user_id in str(params.get("receiver_id")).split(";"):
            if user_id.isdigit():
                sql = NoteSqlMap.check_name.format(**{"user_id":int(user_id)})
                res = mysql_tools.select_one(sql)
                receiver += res.get("user_name") + ";"
            else:
                return err_response(210)
        receiver = receiver[0:-1]
        params["receiver"] = receiver
        sql_note_add = NoteSqlMap.note_add.format(**params)
    else:
        receiver = "null"
        params["receiver"] = receiver
        sql_note_add = NoteSqlMap.note_add_no.format(**params)
    mysql_tools.execute_sql(sql_note_add, commit=True)
    note_id = mysql_tools.select_one(NoteSqlMap.GET_ID).get("id")
    return success_response({"note_id": note_id})


def my_note_list(params):
    dict = {
        "user_id": "user_id",
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str": "query_str",
        "catalog_id": "catalog_id",
        "receiver_to_me": "receiver_to_me"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    sql_check_name = NoteSqlMap.check_name.format(**params)
    real_name = mysql_tools.select_one(sql_check_name)
    if not real_name is None:
        params["user_name"] = real_name.get("user_name")
    sql = add_filter(NoteSqlMap.my_note_list, params, ["query_str", "catalog_id", "receiver_to_me"],
                     **NoteSqlMap.FILTER_PARAMS)
    sql += " order by t1.create_time desc"
    sql = sql.format(**params)
    result = mysql_tools.select_all(sql)
    # if params.get("isall") is not True:
    if params.get("isall") != 1:
        if isinstance(result,JsonResponse):
            return result
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        sql_note_read_name = NoteSqlMap.note_read_name.format(**{"note_id": res["note_id"]})
        name = mysql_tools.select_all(sql_note_read_name)
        sql_note_read_count = NoteSqlMap.note_read_count.format(**{"note_id": res["note_id"]})
        count = mysql_tools.select_one(sql_note_read_count)
        if not count is None:
            res["read_times"] = count.get("read_times") if count.get("read_times") else 0
        else:
            res["read_times"] = 0
        if res["create_time"]: res["create_time"] = str(res["create_time"])
        name_list = []
        if isinstance(name,JsonResponse):
            return name
        for name_one in name:
            real_name = name_one.get("real_name")
            name_list.append(real_name)
        res["read_name"] = name_list
    return success_response(result)


def subordinates_note_list(params):
    dict = {
        "user_id": "user_id",
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str": "query_str",
        "catalog_id": "catalog_id",
        "is_read": "is_read"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    sql = NoteSqlMap.FIND_ROLE_BY_ID.format(**params)
    role_id = mysql_tools.select_one(sql).get("role_value")
    if isinstance(role_id, JsonResponse):
        return role_id
    # if not role_id is None:
    #     role_id = role_id.get("role_id") if role_id.get("role_id") else 7
    # else:
    #     role_id = 7
    if role_id <= 1:
        sql_subordinates_id = NoteSqlMap.subordinates_id_list_all.format(**params)
    else:
        sql_subordinates_id = NoteSqlMap.subordinates_id_list.format(**params)
    subordinates_id_all = mysql_tools.select_all(sql_subordinates_id)
    if isinstance(subordinates_id_all,JsonResponse):
        return subordinates_id_all
    result = []
    params["reader_id"] = params.get("user_id")
    for subordinates_id in subordinates_id_all:
        params["user_id"] = subordinates_id.get("user_id")
        if params["user_id"] is None:
            continue
        sql = add_filter(NoteSqlMap.my_note_list, params, ["query_str", "catalog_id"],
                         **NoteSqlMap.FILTER_PARAMS)
        if params.get("is_read") == 1:
            sql += " and t1.note_id in (select note_id from aoa_note_read where user_id={reader_id})"
        elif params.get("is_read") == 0:
            sql += " and t1.note_id not in (select note_id from aoa_note_read where user_id={reader_id})"
        sql = sql.format(**params)
        result_all = mysql_tools.select_all(sql)
        if not result_all:
            continue
        result.extend(result_all)
    # if params.get("isall") is not True:
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    if isinstance(result, JsonResponse):
        return result
    for res in result:
        sql_note_read_name = NoteSqlMap.note_read_name.format(note_id=res.get("note_id"))
        name = mysql_tools.select_all(sql_note_read_name)
        sql_note_read_count = NoteSqlMap.note_read_count.format(note_id=res.get("note_id"))
        count = mysql_tools.select_one(sql_note_read_count)
        res["read_times"] = count["read_times"]
        res["create_time"] = str(res["create_time"])
        name_list = []
        for name_one in name:
            name_list.append(name_one["real_name"])
        res["read_name"] = name_list
    result.sort(key=lambda z:z["create_time"], reverse=True)
    return success_response(result)


def check_note(params):
    dict = {
        "note_id": "note_id",
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210)
    sql = NoteSqlMap.check_note.format(**params)
    result = mysql_tools.select_one(sql)
    if not result:
        return success_response({})
    sql_note_read_name = NoteSqlMap.note_read_name.format(**params)
    name = mysql_tools.select_all(sql_note_read_name)
    sql_note_read_count = NoteSqlMap.note_read_count.format(**params)
    count = mysql_tools.select_one(sql_note_read_count)
    result["read_times"] = count.get("read_times")
    if result.get("create_time"):
        result["create_time"] = str(result["create_time"])
    name_list = []
    for name_one in name:
        name_list.append(name_one["real_name"])
    result["read_name"] = name_list
    if not mysql_tools.select_one(NoteSqlMap.CHECK_READ.format(**params)):
        sql = NoteSqlMap.INSERT_READ.format(**params)
        mysql_tools.execute_sql(sql, commit=True)
    return success_response(result)


@format_response
def index(request):
    return com_views(request, {
        "note_add": note_add,       # 日志添加
        "my_note_list": my_note_list,       # 我的日志列表
        "subordinates_note_list": subordinates_note_list,  # 下属日志列表
        "check_note": check_note,       # 查看日志
        "all_note_classify": all_note_classify      # 所有日志分类
    })
